package com.etoak.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.etoak.common.core.exception.CustomException;
import com.etoak.common.core.properties.ImageProperties;
import com.etoak.common.core.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/upload")
public class UploadController {

    // common-web => common-jwt => common-core
    @Autowired
    ImageProperties imageProperties;

    @PostMapping("/image")
    public ResultVO<String> uploadImage(MultipartFile pic) throws IOException {
        if(ObjectUtil.isEmpty(pic) || pic.isEmpty()){
            throw new CustomException("文件不允许为空");
        }

        String contentType = pic.getContentType();
        if(!imageProperties.getTypeList().contains(contentType)){
            String types = imageProperties.getTypeList().stream()
                    .map(x -> x.split("/")[1])
                    .collect(Collectors.joining(";"));
            throw new CustomException("仅允许"+types+"类型的文件");
        }

        //3.创建文件上传目录
        String location = imageProperties.getLocation();
        File parent = new File(location);
        if(!parent.exists()){
            parent.mkdirs();
        }

        //4.创建文件的上传名称
        String originalFilename = pic.getOriginalFilename();
        String fileName = IdUtil.simpleUUID()+originalFilename.substring(originalFilename.lastIndexOf(StrUtil.DOT));

        File target = new File(parent, fileName);
        try{
            pic.transferTo(target);
        }catch (Exception e){
            e.printStackTrace();
        }

        //拼装返回数据
        String result =imageProperties.getPrefix().endsWith(StrUtil.SLASH)?
        imageProperties.getPrefix()+fileName:
        imageProperties.getPrefix()+StrUtil.SLASH+fileName;

        return ResultVO.success(result);

    }

}
